package cz.data.common.database.dialect;

import com.alibaba.fastjson.JSONObject;
import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * MySql 数据库方言
 */
public class MySqlDialect extends AbstractDbDialect {

    @Override
    public RowMapper<DbColumn> columnMapper() {
        return (ResultSet rs, int rowNum) -> {
            DbColumn entity = new DbColumn();
            entity.setColName(rs.getString("COLNAME"));
            entity.setDataType(rs.getString("DATATYPE"));
            entity.setDataLength(rs.getString("DATALENGTH"));
            entity.setDataPrecision(rs.getString("DATAPRECISION"));
            entity.setDataScale(rs.getString("DATASCALE"));
            entity.setColKey("PRI".equals(rs.getString("COLKEY")));
            entity.setNullable("YES".equals(rs.getString("NULLABLE")));
            entity.setColPosition(rs.getInt("COLPOSITION"));
            entity.setDataDefault(rs.getString("DATADEFAULT"));
            entity.setColComment(rs.getString("COLCOMMENT"));
            return entity;
        };
    }

    @Override
    public RowMapper<DbTable> tableMapper() {
        return (ResultSet rs, int rowNum) -> {
            DbTable entity = new DbTable();
            entity.setTableName(rs.getString("TABLENAME"));
            entity.setTableComment(rs.getString("TABLECOMMENT"));
            String tableType = rs.getString("TABLETYPE");
            if (StringUtils.isNotBlank(tableType)) {
                entity.setTableType(tableType);
            }
            return entity;
        };
    }

    @Override
    public PreparedStatementCreator upsertSQL(List<JSONObject> jsonList, String table, List<String> primaryKeys, String[] insertFields, String[] updateFields) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO `").append(table).append("`");
        sb.append(Stream.of(insertFields).map(this::escape).collect(Collectors.joining(",", "(", ")")));
        sb.append(" VALUES");
        sb.append(Stream.of(insertFields).map(f -> "?").collect(Collectors.joining(",", "(", ")")));
        sb.append(" ON DUPLICATE KEY UPDATE ");
        sb.append(Stream.of(updateFields)
                .map(this::escape)
                .map(f -> f + " = ?")
                .collect(Collectors.joining(","))
        );
        String sql = sb.toString();
        return con -> {
            con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            PreparedStatement ps = con.prepareStatement(sql);
            for (JSONObject json : jsonList) {
                int i = 0;
                for (String insertField : insertFields) {
                    setObjectOrNULL(ps, ++i, json.get(insertField));
                }
                for (String updateField : updateFields) {
                    setObjectOrNULL(ps, ++i, json.get(updateField));
                }
                ps.addBatch();
            }
            return ps;
        };
    }

    private String escape(String field) {
        return "`" + field + "`";
    }

}
